/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ServerGui.java
 *
 * Created on Nov 30, 2009, 12:16:29 PM
 */

package sahd.broker.server;
import Services.ProductServices;
import Services.exception.ServiceException;
import com.mysql.jdbc.StringUtils;
import file.reader.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import sahd.broker.iONetMessageManager.Message;
import sahd.broker.proxys.ProxyServer;
import sahd.nicTools.NICTool;

/**
 *
 * @author Romms
 */
public class ServerGui extends javax.swing.JFrame implements Observer{
    private static final String servicesFile="D:\\FMAT\\CES\\Collaboration\\sahd\\serverServices.srv";
    private int outPort=8888;
    private int entryProt=7777;
    private String initialBrokerIp="192.168.1.67";
    private Message message;
    private ProxyServer proxyServer;
    private ArrayList<Service> services;

    private static final int SERVICE_PROTOCOL=0;
    private static final int SERVICE_NAME=1;
    ProductServices productServices;

    /** Creates new form ServerGui */
    public ServerGui() throws UnknownHostException, SocketException {
        try {
            initComponents();
            ProductServices productServices = new ProductServices();
            services = new ArrayList<Service>();
            proxyServer = new ProxyServer(this, outPort, entryProt, initialBrokerIp);
            this.registerServer();
            this.registerServices(services);
        } catch (IOException ex) {
            Logger.getLogger(ServerGui.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        btnStart = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txtLog.setColumns(20);
        txtLog.setRows(5);
        jScrollPane1.setViewportView(txtLog);

        jLabel1.setText("Log:");

        btnStart.setText("Start");
        btnStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
                        .addComponent(btnStart))
                    .addComponent(jLabel1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnStart)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed
        this.registerServer();
    }//GEN-LAST:event_btnStartActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new ServerGui().setVisible(true);
                } catch (UnknownHostException ex) {
                    Logger.getLogger(ServerGui.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SocketException ex) {
                    Logger.getLogger(ServerGui.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }



    private void eventHandler(Message message) throws IOException{
        this.message=message;
        switch(this.message.getProtocol()){
            case ServerProtocol.SUCCESFUL_REGISTER:
                this.txtLog.append("Servicdor registrado." + '\n');
                break;
                
            case ServiceProtocol.GET_AMOUNT_USER:
                this.getUserAmmount(message.getContent().toString());
                this.txtLog.append("Servicdor registrado." + '\n');
                break;

            case ServiceProtocol.DELETE_PRODUCT:
                this.deleteProduct(Integer.parseInt(message.getContent().toString()));
                break;
            default:
                this.proxyServer.shipMessage("Service unavailable", ServerProtocol.UNAVAILABLE_SERVICE);
        }

    }


    private void deleteProduct(int idProduct){
        try {
                this.proxyServer.shipMessage(productServices.deleteProduct(idProduct), ServerProtocol.RESPONSE_REQUEST, message.getOriginalSourceIPAddress(), message.getServiceRequestedProtocol());
            } catch (IOException ex) {
                Logger.getLogger(ServerGui.class.getName()).log(Level.SEVERE, null, ex);
            }catch (ServiceException ex) {
            Logger.getLogger(ServerGui.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void getUserAmmount(String userAccountName){
  
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnStart;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtLog;
    // End of variables declaration//GEN-END:variables

    public void update(Observable o, Object arg) {
        try {
            eventHandler((Message) arg);
        } catch (IOException ex) {
            Logger.getLogger(ServerGui.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void registerServer(){
        try {
            ServerMachine serverMachine = new ServerMachine(NICTool.getNICIPAddress(),
                    NICTool.getNICMacAddress());
            this.proxyServer.shipMessage(serverMachine, ServerProtocol.REGISTER_SERVER);
        } catch (IOException ex) {
            System.out.println("No hay broker disponible");
        }
    }

    public void registerServices(ArrayList<Service> listOfServices) throws IOException{
        this.proxyServer.shipMessage(getListOfServerServices(), ServerProtocol.REGISTER_LIST_OF_SERVICES);
    }

    private ArrayList <Service> getListOfServerServices(){
        try {
            FileReader fileReader = new FileReader(servicesFile);
            ArrayList<String> listOfServices = fileReader.getFileContent();
            String serverIpAddress=NICTool.getNICIPAddress();

            ArrayList<String>serviceProperties = new ArrayList<String>();

            for (int serviceIndex = 0; serviceIndex < listOfServices.size();serviceIndex++) {
                serviceProperties = (ArrayList<String>) StringUtils.split(listOfServices.get(serviceIndex),"|",true);
                services.add(new Service(Integer.parseInt(serviceProperties.get(SERVICE_PROTOCOL)) ,
                        serviceProperties.get(SERVICE_NAME).toString(), serverIpAddress));
            }
            return services;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ServerGui.class.getName()).log(Level.SEVERE, null, ex);
            return services;
        }
    }


}
